package edu.java.ishop.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.inject.Named;

import org.springframework.security.crypto.password.PasswordEncoder;

@Named
public class PasswordHelper implements PasswordEncoder{

	
	private MessageDigest md;
	public PasswordHelper() {
	
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			//TODO:Log.Error
		}
	}
	@Deprecated
	public static String hash(String password) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			return password;
		}
		md.update(password.getBytes());

		byte byteData[] = md.digest();

		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			String hex = Integer.toHexString(0xff & byteData[i]);
			if (hex.length() == 1)
				hexString.append('0');
			hexString.append(hex);
		}

		return hexString.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(hash("user"));
		System.out.println(hash("admin"));
	}

	@Override
	public String encode(CharSequence rawPassword) {
		
		if(md==null){
			return rawPassword.toString();
		}
		md.update(rawPassword.toString().getBytes());

		byte byteData[] = md.digest();

		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			String hex = Integer.toHexString(0xff & byteData[i]);
			if (hex.length() == 1)
				hexString.append('0');
			hexString.append(hex);
		}

		return hexString.toString();
	}

	@Override
	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		// TODO Auto-generated method stub
		return encode(rawPassword).equals(encodedPassword);
	}
	
}
